﻿ 
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using SHKF.B2C.MeiTuanShanGou.BLL;
using SHKF.B2C.BLL.Center;
using SHKF.B2C.BLL.LM;
using SHKF.B2C.MeiTuanShanGou.Model.Dto;
using SHKF.B2C.MeiTuanShanGou.Model.Entity.Order;
using SHKF.B2C.MeiTuanShanGou.Model.Push.Refund; 
using SHKF.B2C.Model;
using SHKF.B2C.Model.Entity.Center; 
using SHKF.B2C.Model.Entity.LM;　 
using System;
using System.Collections.Generic; 
using System.Linq; 
using System.Threading.Tasks;
using System.Web;
using SHKF.B2C.MeiTuanShanGou.Model.Dto.OrderRefundDetail;

namespace SHKF.B2C.MeiTuanShanGou.Service.Controllers
{
    /// <summary>
    /// 退款
    /// </summary>
    [Route("[controller]")]
    [ApiController]
    public class RefundController : Base2Controller
    {
        private readonly ShopMapBLL shopMapBll;
        private readonly MedicineBLL medicineBLL;
        private readonly MtsgOrderBLL mtsgOrderBLL;
        private readonly RetrunOrderBLL retrunOrderBLL;

        public RefundController(  
              ShopMapBLL shopMapBll,
              MedicineBLL medicineBLL,
              MtsgOrderBLL mtsgOrderBLL,
              RetrunOrderBLL retrunOrderBLL,
              IServiceProvider serviceProvider,
          ILogger<RefundController> logger) : base(serviceProvider, logger)
        {
            this.shopMapBll = shopMapBll;
            this.medicineBLL = medicineBLL;
            this.mtsgOrderBLL = mtsgOrderBLL;
            this.retrunOrderBLL = retrunOrderBLL;
        }


        /// <summary>
        /// 全部退款
        /// </summary>
        /// <param name="order"></param>
        /// <returns></returns>
        [HttpPost("CallBack")]
        public BaseDataDto CallBack([FromQuery] RefundPush push)
        {
            try
            {
                if (push != null && push.app_poi_code > 0)
                {
                    string json = JsonConvert.SerializeObject(push);

                    base.AddLog("Refund-CallBack->" + json);

                    base.WriteInformation("Refund-CallBack", "jsonData:" + json);

                    //因為美團的单子暂时存在美团的数据库里,以后统一存储在pte_lm
                    OrderContentEntity orderContentEntity = this.mtsgOrderBLL.Query(push.app_poi_code, push.order_id);

                    ReturnOrderContentEntity orderEntity = new ReturnOrderContentEntity();

                    int shopSN = 0;
                    ShopMapEntity shopMap = this.shopMapBll.GetShop(push.app_poi_code, PlatformEnum.Mtsg);
                    if (shopMap != null)
                    {
                        shopSN = shopMap.ShopSN;
                    }
                    orderEntity.ShopSN = shopSN;
                    orderEntity.app_poi_code = push.app_poi_code;
                    orderEntity.status = push.status;
                    orderEntity.order_id = push.order_id;

                    orderEntity.total = orderContentEntity.total;
                    orderEntity.reason = HttpUtility.UrlDecode(push.reason);

                    orderEntity.Platform = PlatformEnum.Mtsg;
                    orderEntity.ctime = DateTimeUtil.TimeStampToDateTime(push.ctime);
                    orderEntity.pDate = DateTime.Now;

                    List<ReturnOrderDetailEntity> list = new List<ReturnOrderDetailEntity>();

                    List<OrderDetailEntity> detailList = this.mtsgOrderBLL.QueryDetail(orderContentEntity.SN);

                    //明细
                    foreach (OrderDetailEntity food in detailList)
                    {
                        ReturnOrderDetailEntity detail = new ReturnOrderDetailEntity();
                        detail.FKSN = 0;
                        detail.app_medicine_code = food.app_medicine_code;
                        detail.product_name = food.product_name;
                        detail.price = food.price;
                        detail.qty = food.qty;
                        detail.upc = food.upc;
                        //detail.spec = food.sp;
                        detail.box_num = food.box_num;
                        detail.box_price = food.box_price;
                        detail.refund_price = food.price;
                        //detail.ProductSN = food.ProductSN;
                        detail.unit = food.unit;

                        list.Add(detail);
                    }

                    this.retrunOrderBLL.SaveAll(orderEntity, list);　
                }
            }
            catch (Exception ex)
            {
                //this.segContext.Context.Span.ErrorOccurred(ex, null);
                base.WriteException("CallBack", ex);
            }
　
            BaseDataDto dto = new BaseDataDto();
            dto.data = "ok";
            return dto;
        }


        /// <summary>
        /// 部分退款
        /// </summary>
        /// <param name="order"></param>
        /// <returns></returns>
        [HttpPost("Part/CallBack")]
        public async Task<BaseDataDto> PartCallBack([FromForm] PartRefundPush push)
        {
            try
            { 
                if (push != null && push.app_poi_code > 0)
                {
                    string json = JsonConvert.SerializeObject(push);

                    base.AddLog("Refund-Part-CallBack->" + json);

                    base.WriteInformation("RefundPart-CallBack", "jsonData:" + json);　
                    ReturnOrderContentEntity orderEntity = new ReturnOrderContentEntity();

                    int shopSN = 0;
                    ShopMapEntity shopMap = this.shopMapBll.GetShop(push.app_poi_code, PlatformEnum.Mtsg);
                    if (shopMap != null)
                    {
                        shopSN = shopMap.ShopSN;
                    }
                    long app_poi_code = push.app_poi_code;
                    long order_id = push.order_id;

                    orderEntity.ShopSN = shopSN;
                    orderEntity.app_poi_code = push.app_poi_code;
                    orderEntity.status = push.status;
                    orderEntity.order_id = push.order_id;　
                    orderEntity.total = push.money;
                    orderEntity.reason = HttpUtility.UrlDecode(push.reason);　
                    orderEntity.Platform = PlatformEnum.Mtsg;
                    orderEntity.ctime = DateTimeUtil.TimeStampToDateTime(push.ctime);
                    orderEntity.pDate = DateTime.Now;


                    //账单相关信息
                    List<ReturnOrderAccountEntity> aefundList = await CreateReturnOrderAccount(app_poi_code, order_id, push.refund_id); ;

                    List<ReturnOrderDetailEntity> list = new List<ReturnOrderDetailEntity>();

                    //明细 
                    List<Food> foods = JsonConvert.DeserializeObject<List<Food>>(push.food);
                    foreach (Food food in foods)
                    {
                        ReturnOrderDetailEntity detail = new ReturnOrderDetailEntity();
                        detail.FKSN = 0;
                        detail.app_medicine_code = food.app_medicine_code;
                        detail.product_name = food.food_name;
                        detail.price = food.food_price;
                        detail.qty = food.count;
                        detail.upc = food.upc;
                        detail.spec = food.spec;
                        detail.box_num = food.box_num;
                        detail.box_price = food.box_price;
                        detail.refund_price = food.refund_price; 
                        detail.unit = "";
                        detail.pDate = DateTime.Now;
                        list.Add(detail);
                    }

                    this.retrunOrderBLL.SaveAll(orderEntity, list, aefundList);
                } 
            }
            catch (Exception ex)
            {
                //this.segContext.Context.Span.ErrorOccurred(ex, null);
                base.WriteException("CallBack", ex);
            }

            BaseDataDto dto = new BaseDataDto();
            dto.data = "ok";
            return dto;
        }

        private async Task<List<ReturnOrderAccountEntity>> CreateReturnOrderAccount(long app_poi_code, long order_id, long refund_id)
        {
            List<ReturnOrderAccountEntity> aefundList = new List<ReturnOrderAccountEntity>();

            await base.GetMtsgToken(app_poi_code);

            OrderRefundDetailDto dto2 = await this.httpClientMeiTuanShanGou.GetOrderRefundDetail(order_id, 2);
            if (dto2 != null && dto2.data != null && dto2.data.Count > 0)
            {
                List<OrderRefundDetailData> data = dto2.data;
                OrderRefundDetailData orderRefundDetailData = data.Find((a) => a.refund_id == refund_id);

                refund_partial_estimate_charge refund = orderRefundDetailData.refund_partial_estimate_charge;
                if (orderRefundDetailData != null && refund != null)
                {
                    //本次退款商品的总金额，不含包装盒费，单商品总价=商品原价+赠品原价，位元
                    ReturnOrderAccountEntity returnOrderAccountEntity = new ReturnOrderAccountEntity();
                    returnOrderAccountEntity.KeyWord = "total_food_amount";
                    returnOrderAccountEntity.OrderSN = order_id;
                    returnOrderAccountEntity.Refund_ID = refund_id;
                    returnOrderAccountEntity.Title = "商品的总金额";
                    returnOrderAccountEntity.Value = refund.total_food_amount;
                    aefundList.Add(returnOrderAccountEntity);

                    //本次退款商品包装盒费总价，单位元
                    returnOrderAccountEntity = new ReturnOrderAccountEntity();
                    returnOrderAccountEntity.KeyWord = "box_amount";
                    returnOrderAccountEntity.OrderSN = order_id;
                    returnOrderAccountEntity.Refund_ID = refund_id;
                    returnOrderAccountEntity.Title = "商品包装盒费总价";
                    returnOrderAccountEntity.Value = refund.box_amount;
                    aefundList.Add(returnOrderAccountEntity);

                    //本次退款商家活动费用总支出成本，含赠品成本，单位元
                    returnOrderAccountEntity = new ReturnOrderAccountEntity();
                    returnOrderAccountEntity.KeyWord = "activity_poi_amount";
                    returnOrderAccountEntity.OrderSN = order_id;
                    returnOrderAccountEntity.Refund_ID = refund_id;
                    returnOrderAccountEntity.Title = "商家活动费用总支出成本";
                    returnOrderAccountEntity.Value = refund.activity_poi_amount;
                    aefundList.Add(returnOrderAccountEntity);

                    //本次退款美团活动补贴总金额，单位元 
                    returnOrderAccountEntity = new ReturnOrderAccountEntity();
                    returnOrderAccountEntity.KeyWord = "activity_meituan_amount";
                    returnOrderAccountEntity.OrderSN = order_id;
                    returnOrderAccountEntity.Refund_ID = refund_id;
                    returnOrderAccountEntity.Title = "美团活动补贴总金额";
                    returnOrderAccountEntity.Value = refund.activity_meituan_amount;
                    aefundList.Add(returnOrderAccountEntity);

                    //本次退款代理商活动承担金额，单位元
                    returnOrderAccountEntity = new ReturnOrderAccountEntity();
                    returnOrderAccountEntity.KeyWord = "activity_agent_amount";
                    returnOrderAccountEntity.OrderSN = order_id;
                    returnOrderAccountEntity.Refund_ID = refund_id;
                    returnOrderAccountEntity.Title = "代理商活动承担金额";
                    returnOrderAccountEntity.Value = refund.activity_agent_amount;
                    aefundList.Add(returnOrderAccountEntity);

                    //本次退款平台服务费总金额，单位元
                    returnOrderAccountEntity = new ReturnOrderAccountEntity();
                    returnOrderAccountEntity.KeyWord = "platform_charge_fee";
                    returnOrderAccountEntity.OrderSN = order_id;
                    returnOrderAccountEntity.Refund_ID = refund_id;
                    returnOrderAccountEntity.Title = "平台服务费总金额";
                    returnOrderAccountEntity.Value = refund.platform_charge_fee;
                    aefundList.Add(returnOrderAccountEntity);

                    //结算金额，单位元
                    returnOrderAccountEntity = new ReturnOrderAccountEntity();
                    returnOrderAccountEntity.KeyWord = "settle_amount";
                    returnOrderAccountEntity.OrderSN = order_id;
                    returnOrderAccountEntity.Refund_ID = refund_id;
                    returnOrderAccountEntity.Title = "结算金额";
                    returnOrderAccountEntity.Value = refund.settle_amount;
                    aefundList.Add(returnOrderAccountEntity);

                    //商家活动支出分摊到商品上的优惠总金额，单位元
                    returnOrderAccountEntity = new ReturnOrderAccountEntity();
                    returnOrderAccountEntity.KeyWord = "productpreferences";
                    returnOrderAccountEntity.OrderSN = order_id;
                    returnOrderAccountEntity.Refund_ID = refund_id;
                    returnOrderAccountEntity.Title = "商家活动支出分摊到商品上的优惠总金额";
                    returnOrderAccountEntity.Value = refund.productpreferences;
                    aefundList.Add(returnOrderAccountEntity);

                    //商家活动支出未分摊到商品上的总金额，单位元 
                    returnOrderAccountEntity = new ReturnOrderAccountEntity();
                    returnOrderAccountEntity.KeyWord = "not_productpreferences";
                    returnOrderAccountEntity.OrderSN = order_id;
                    returnOrderAccountEntity.Refund_ID = refund_id;
                    returnOrderAccountEntity.Title = "商家活动支出未分摊到商品上的总金额";
                    returnOrderAccountEntity.Value = refund.not_productpreferences;
                    aefundList.Add(returnOrderAccountEntity);

                }
            }

            return aefundList;
        }

    }
}
